package com.gongpingjialoan.activity.car;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.gongpingjialoan.R;
import com.gongpingjialoan.activity.main.BaseActivity;
import com.gongpingjialoan.adapter.car.PriceAdjustmentRecordAdapter;
import com.gongpingjialoan.api.API;
import com.gongpingjialoan.bean.car.PriceAdjustmentBean;
import com.gongpingjialoan.imageload.ImageLoad;
import com.gongpingjialoan.network.NetDataJson;
import com.gongpingjialoan.utility.Utils;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * 调价记录
 */
public class PriceAdjustmentRecordActivity extends BaseActivity {

    private NetDataJson detelNetDataJson;

    private NetDataJson remindJson;
    private NetDataJson deleteRemindJson;

    private View loading;

    String car_id;

    TextView brand_nameT, domain_timeT, carNameT, mile_txtT, priceT, eval_priceT, msg1T;

    TextView jiang_zhang_textTextView, foot_priceT, foot_price_changeT, foot_decrease_roomT;

    ImageView picI;

    ListView listview;

    PriceAdjustmentRecordAdapter adapter;

    View viewMain;

    View bootmview, yijiangMainView;

    CheckBox attention;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        isSendData = true;
        action = "detail_priceHistory";
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_price_adjustment_record);
        initView();
    }


    private void initView() {
        setTitle("调价记录");
        car_id = getIntent().getStringExtra("car_id");
        loading = findViewById(R.id.main_loading);
        viewMain = findViewById(R.id.main);
        viewMain.setVisibility(View.GONE);
        bootmview = findViewById(R.id.bootmview);
        bootmview.setVisibility(View.GONE);
        brand_nameT = (TextView) findViewById(R.id.brand_name);
        domain_timeT = (TextView) findViewById(R.id.domain_time);
        carNameT = (TextView) findViewById(R.id.carName);

        mile_txtT = (TextView) findViewById(R.id.mile_text);
        priceT = (TextView) findViewById(R.id.price);
        eval_priceT = (TextView) findViewById(R.id.eval_price);
        msg1T = (TextView) findViewById(R.id.msg1);
        picI = (ImageView) findViewById(R.id.pic);
        attention = (CheckBox) findViewById(R.id.attention);

        View footView = LayoutInflater.from(this).inflate(R.layout.footview_price_adjustment_record_list, null);
        foot_priceT = (TextView) footView.findViewById(R.id.price);
        yijiangMainView = footView.findViewById(R.id.yijiang_mainlinear);
        foot_price_changeT = (TextView) footView.findViewById(R.id.price_change);
        foot_decrease_roomT = (TextView) footView.findViewById(R.id.decrease_room);
        jiang_zhang_textTextView = (TextView) footView.findViewById(R.id.jiang_zhang_text);
        adapter = new PriceAdjustmentRecordAdapter(this);
        listview = (ListView) findViewById(R.id.listview);
        listview.addFooterView(footView);
        listview.setAdapter(adapter);


        getMaintainData();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if (detelNetDataJson != null) {
            detelNetDataJson.cancelTask();
            detelNetDataJson = null;
        }

        if (remindJson != null) {
            remindJson.cancelTask();
            remindJson = null;
        }

        if (deleteRemindJson != null) {
            deleteRemindJson.cancelTask();
            deleteRemindJson = null;
        }

    }

    public void setAttention() {
        attention.setOnCheckedChangeListener(new CheckBox.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked == true) {
                    attention();
                } else {
                    deleteRemind();
                }
            }
        });

    }

    /**
     * 关注
     */
    private void attention() {
        if (remindJson == null) {
            remindJson = new NetDataJson(new NetDataJson.OnNetDataJsonListener() {
                @Override
                public void onDataJsonError(String errorMessage) {
                    loading.setVisibility(View.GONE);
                    Toast.makeText(PriceAdjustmentRecordActivity.this, errorMessage, Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onDataJsonUpdate(JSONObject json) {
                    EventBus.getDefault().post("remind");
                    loading.setVisibility(View.GONE);
                }
            });

        }
        remindJson.setUrl(API.price_change_remind);
        remindJson.addParam("car_id", car_id);
        remindJson.request("post");
    }

    /**
     * 取消关注
     */
    private void deleteRemind() {
        if (deleteRemindJson == null) {
            deleteRemindJson = new NetDataJson(new NetDataJson.OnNetDataJsonListener() {
                @Override
                public void onDataJsonError(String errorMessage) {
                    loading.setVisibility(View.GONE);
                    Toast.makeText(PriceAdjustmentRecordActivity.this, errorMessage, Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onDataJsonUpdate(JSONObject json) {
                    EventBus.getDefault().post("delete_remind");
                    loading.setVisibility(View.GONE);
                }
            });

        }
        deleteRemindJson.setUrl(API.delete_price_change_remind);
        deleteRemindJson.addParam("car_ids", car_id);
        deleteRemindJson.request("post");
    }

    /**
     * 获取车辆信息调价信息
     */
    private void getMaintainData() {
        if (detelNetDataJson == null) {
            detelNetDataJson = new NetDataJson(new NetDataJson.OnNetDataJsonListener() {
                @Override
                public void onDataJsonError(String errorMessage) {
                    loading.setVisibility(View.GONE);
                    Toast.makeText(PriceAdjustmentRecordActivity.this, errorMessage, Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onDataJsonUpdate(JSONObject json) {
                    try {
                        loading.setVisibility(View.GONE);
                        JSONObject car_info = json.getJSONObject("car_info");

                        brand_nameT.setText(car_info.getString("model_zh"));

                        String title = car_info.getString("model_detail_zh");
                        if (TextUtils.isEmpty(title)) {
                            title = car_info.getString("title");
                        }
                        carNameT.setText(title);
                        mile_txtT.setText(car_info.getString("mile") + "万公里/" + car_info.getString("year") + "年上牌");
                        priceT.setText(car_info.getString("price"));
                        eval_priceT.setText(car_info.getString("eval_price"));
                        ImageLoad.LoadImage(picI, car_info.getString("thumbnail"), R.drawable.car_loading, R.drawable.car_no,PriceAdjustmentRecordActivity.this);

                        JSONObject price_history = json.getJSONObject("price_history");
                        boolean is_reminding = price_history.getBoolean("is_reminding");
                        attention.setChecked(is_reminding);
                        setAttention();

                        int online_time = Integer.parseInt(price_history.getString("online_time"));
                        if (online_time == 0) {
                            domain_timeT.setText("今天发布");
                        } else {
                            domain_timeT.setText(online_time + "天前发布");
                        }
                        msg1T.setText(price_history.getString("message"));

                        JSONArray price_list = price_history.getJSONArray("price_list");

                        List<PriceAdjustmentBean> list = new ArrayList();
                        for (int i = 0; i < price_list.length(); i++) {
                            JSONObject jo = price_list.getJSONObject(i);
                            PriceAdjustmentBean bean = new PriceAdjustmentBean();
                            bean.setIs_lowest(jo.getBoolean("is_lowest"));
                            bean.setPrice(jo.getString("price"));
                            bean.setCreate_time(jo.getString("create_time"));
                            bean.setPrice_change(jo.getString("price_change"));
                            list.add(bean);
                        }


                        foot_priceT.setText(car_info.getString("price"));
                        //            当前标价15万，未降过价（只有首次标价 or 首次标价=最低标价）
//            当前标价15万，可降价0.5万（当前标价>=首次标价 and 当前标价>最低标价）
//            当前标价15万，已降价0.5万（当前标价<首次标价 and 当前标价=最低标价）
//            当前标价15万，已降价0.5万，还可降0.1万（当前标价<首次标价 and 当前标价>最低标价）
                        if (list.size() == 1) {
                            foot_decrease_roomT.setText(", 未降过价");
                            yijiangMainView.setVisibility(View.GONE);
                        } else {
                            if (list.get(0).is_lowest()) {
                                foot_decrease_roomT.setText(", 未降过价");
                                yijiangMainView.setVisibility(View.GONE);
                            }
                            float decreasePrice = Float.parseFloat(price_history.getString("price_decrease"));
                            if (decreasePrice < 0) {
                                jiang_zhang_textTextView.setText(", 可降价");
                                foot_price_changeT.setTextColor(getResources().getColor(R.color.ed8));
                                yijiangMainView.setVisibility(View.VISIBLE);
                                foot_decrease_roomT.setVisibility(View.GONE);
                            } else {
                                yijiangMainView.setVisibility(View.VISIBLE);
                                jiang_zhang_textTextView.setText(", 已降价");
                                foot_price_changeT.setTextColor(getResources().getColor(R.color.ed8));
                                float decrease_room = Float.valueOf(price_history.getString("decrease_room"));
                                if (decrease_room == 0) {
                                    foot_decrease_roomT.setVisibility(View.GONE);
                                } else {
                                    String decreaseprice = price_history.getString("decrease_room");
                                    String title_p = ", 还可降" + decreaseprice + "万";
                                    foot_decrease_roomT.setText(Utils.changeColor(PriceAdjustmentRecordActivity.this, title_p, 5, 5 + decreaseprice.length(), R.color.ed8));
                                }
                            }
                            foot_price_changeT.setText(Math.abs(decreasePrice) + "");
                        }
                        adapter.setData(list);
                    } catch (JSONException e) {

                    }
                    viewMain.setVisibility(View.VISIBLE);
                    bootmview.setVisibility(View.VISIBLE);
                }
            });

        }
        detelNetDataJson.setUrl(API.price_Adjustment_Record);
        detelNetDataJson.addParam("car_id", car_id);
        detelNetDataJson.request("get");

    }
}
